from wtforms import fields as f

from tipfy.i18n import lazy_gettext
from tipfyext.wtforms import Form

ERROR_MSG = lazy_gettext('A problem occurred. Please correct the errors '
                         'listed in the form.')
SUCCESS_MSG = lazy_gettext('Done.')


class BaseForm(Form):
    def validate_with_messages(self, func, success_msg=None, error_msg=None):
        if self.validate():
            func('success', success_msg or unicode(SUCCESS_MSG), flash=True,
                life=5)

            return True

        func('error', error_msg or unicode(ERROR_MSG), life=None)
        return False


class StringListField(f.TextField):
    """
    A field for tags stored in a `db.StringListProperty`.
    """
    def __init__(self, split_separator=u',', join_separator=u', ', *args,
        **kwargs):
        super(StringListField, self).__init__(*args, **kwargs)
        self.split_separator = split_separator
        self.join_separator = join_separator

    def process_data(self, value):
        self.data = self._to_list(value)

    def process_formdata(self, valuelist):
        if valuelist:
            self.data = self._to_list(valuelist[0])
        else:
            self.data = []

    def _value(self):
        return self._to_string(self.data)

    def _to_list(self, value):
        if not value:
            return []

        if isinstance(value, list):
            return value

        res = []
        for v in value.split(self.split_separator):
            v = v.strip()
            if v:
                res.append(v)

        return res

    def _to_string(self, value):
        if not value:
            return u''

        if isinstance(value, basestring):
            return value

        return self.join_separator.join(value)


TagsField = StringListField
